﻿namespace Guia.Core
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Diagnostics.Contracts;
    using System.Windows.Automation;
    using Guia.Elements;
    using Guia.Locator;
    using System.IO;

    /// <summary>
    /// This class represents a running application
    /// </summary>
    public class Application : IRunnableEntity
    {
        /// <summary>
        /// The underlying process of the application
        /// </summary>
        private Process process;

        /// <summary>
        /// Prevents a default instance of the <see cref="Application"/> class from being created. 
        /// </summary>
        private Application()
        {
        }

        /// <summary>
        /// Starts a new application
        /// </summary>
        /// <param name="path">Path to an executable file</param>
        /// <returns>started application</returns>
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="Win32Exception"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public static Application Start(string path)
        {
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(path), "path is null or empty");
            Application application = new Application();
            string[] subStr = path.Split(new char[] { ' ' }, 2);
            string arguments = string.Empty;
            if (subStr.Length > 1)
            {
                path = subStr[0];
                arguments = subStr[1];
            }

            if (!File.Exists(path))
            {
                throw new ArgumentException("path doesn't exist: " + path);
            }

            application.process = new Process
                                      {
                                          StartInfo =
                                              {
                                                  FileName = @path, 
                                                  Arguments = arguments
                                              }
                                      };
            application.process.Start();
            return application;
        }  

        /// <summary>
        /// Returns the window with the specified Name
        /// </summary>
        /// <param name="name">Name of the window</param>
        /// <returns>Window with the given name</returns>
        /// <exception cref="ArgumentException" />
        public Window GetWindowByName(string name)
        {
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(name));
            SearchCondition searchCondition =
                SearchCondition.ByName(name).And(SearchCondition.ByControlType(ControlType.Window));
            return this.GetWindowBySearchCondition(searchCondition);
        }

        /// <summary>
        /// Returns the window with the specified AutomationId
        /// </summary>
        /// <param name="automationId">AutomationId of the window</param>
        /// <returns>Window with the given AutomationId</returns>
        public Window GetWindowById(string automationId)
        {
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(automationId));
            SearchCondition searchCondition =
                SearchCondition.ByAutomationId(automationId).And(SearchCondition.ByControlType(ControlType.Window));
            return this.GetWindowBySearchCondition(searchCondition);
        }

        /// <summary>
        /// Stops the application
        /// </summary>
        public void Stop()
        {
            if (this.process != null)
            {
                try
                {
                    if (!this.process.HasExited)
                    {
                        this.process.Kill();
                    }
                }
                finally
                {
                    this.process.Dispose();

                    // delete the reference
                    this.process = null;
                }
            }
        }

        /// <summary>
        /// Gets a window by SearchCondition
        /// </summary>
        /// <param name="searchCondition">
        /// The search condition.
        /// </param>
        /// <returns>
        /// The found window or null, if noone was found
        /// </returns>
        /// <exception cref="ArgumentException" />
        private Window GetWindowBySearchCondition(SearchCondition searchCondition)
        {
            Contract.Requires<ArgumentException>(searchCondition != null);
            Contract.Requires(this.process != null);
            return WindowHelper.GetWindowBySearchCondition(searchCondition, this.process.Id);
        }
    }
}
